﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using Kevin.Service.Client.Restful;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Core.Member;
using RiderShop.Mobile.Common.Helper;
using RiderShop.Mobile.ServiceEntity.Purchase;
using RiderShop.Mobile.Common.ThirdEntity;
using Kevin.Shop.Business.Core.Components;
using RiderShop.Mobile.Common.Component;
using Kevin.Comm.Utility;

namespace Kevin.Shop.Business.Service.Entity.Helper
{
    public class WebClientContext : ClientContext
    {
        private string userName;
        private int userId;
        private UserBasicInfo _currentUser;
        public const string StrGroup = "Group";
        public const string StrCategory = "Category";
        public static int CON_PageSize = string.IsNullOrEmpty(ConfigurationManager.AppSettings["CommonPageSize"]) ? 6 : int.Parse(ConfigurationManager.AppSettings["CommonPageSize"]);

        public static WebClientContext Current
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    return new WebClientContext();
                }
                return null;
            }
        }

        public UserBasicInfo CurrentUser
        {
            get
            {
                if (_currentUser == null)
                {
                    _currentUser = CacheUsers.Get(UserName, true);
                }
                return _currentUser;
            }
            set { _currentUser = value; }
        }

        public new int UserId
        {
            get
            {
                if (CurrentUser != null)
                {
                    return CurrentUser.UserId;
                }
                return 0;
            }
        }

        public new string UserName
        {
            get
            {
                if (userName == null && HttpContext.Current != null)
                {
                    userName = HttpContext.Current.User.Identity.Name;
                }
                return userName;
            }
            set { userName = value; }
        }

        public bool IsAuthenticated
        {
            get { return HttpContext.Current.Request.IsAuthenticated; }
        }

        public bool IsWebRequest
        {
            get { return (HttpContext.Current != null); }
        }

        private string returnUrl;
        public string ReturnUrl
        {
            get
            {
                if (returnUrl == null)
                {
                    returnUrl = HttpContext.Current.Request.QueryString["returnUrl"];
                }
                return returnUrl;
            }
            set { returnUrl = value; }
        }

        public string RawUrl
        {
            get { return HttpContext.Current.Request.RawUrl; }
        }

        public string CategorySwitch
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["CategorySwitch"];
            }
        }

        public string SiteName
        {
            get
            {
                var sitemName = ConfigurationManager.AppSettings[CacheKeys.CacheKeySiteName];
                return sitemName;
            }
        }

        public string SiteDescription
        {
            get
            {
                var sitemName = ConfigurationManager.AppSettings[CacheKeys.CacheKeySiteDescription];
                return sitemName;
            }
        }

        public string SiteTheme
        {
            get
            {
                var theme = ConfigurationManager.AppSettings[CacheKeys.CacheKeySiteTheme];
                return string.IsNullOrEmpty(theme) ? "Default".ToLower() : theme.Trim().ToLower();
            }
        }

        public string SiteColor
        {
            get
            {
                var color = System.Configuration.ConfigurationManager.AppSettings[CacheKeys.CacheKeySiteColor];
                return string.IsNullOrEmpty(color) ? ThemeColorType.Default.ToString().ToLower() : color.Trim().ToLower();
            }
        }

        public string CacheKeyDefaultMasterPage
        {
            get
            {
                var theme = ConfigurationManager.AppSettings[CacheKeys.CacheKeyDefaultMasterPage];
                return string.IsNullOrEmpty(theme) ? "_Layout" : theme.Trim().ToLower();
            }
        }


        public int PageSize
        {
            get
            {
                return WebClientContext.CON_PageSize;
            }
        }

        private string paymentType = ConfigurationManager.AppSettings["PaymentType"];

        /// <summary>
        /// 支付类型
        /// </summary>
        public PaymentType OnLinePayment
        {
            get
            {
                int payment = 2;
                int.TryParse(paymentType, out payment);
                return (PaymentType)payment;
            }
        }

        /// <summary>
        /// 从服务端获取当前用户信息
        /// </summary>
        public UserBasicInfo GetCurrentUser()
        {
            return GetCurrentUser(true); ;
        }

        /// <summary>
        /// 从服务端获取当前用户信息
        /// </summary>
        public UserBasicInfo GetCurrentUser(bool isCache)
        {
            return CacheUsers.Get(UserName, isCache); ;
        }

        public static string ReadJsonStringFromRequestBody(Stream requstStrem)
        {
            var byts = new byte[requstStrem.Length];
            requstStrem.Read(byts, 0, byts.Length);
            string req = Encoding.Default.GetString(byts);
            return req;
        }

        public string OpenId
        {
            get
            {
                return KevinCookieManager.Get("openid");
            }
            set
            {
                KevinCookieManager.Set("openid", value, 1000000);
            }
        }

        public SiteSettings SiteSettings
        {
            get
            {
                SiteSettings setting = null;
                if (!KevinCache.Exists(CacheKeys.CacheKeySiteSettings))
                {
                    setting = RestfulHelper.QueryWithSingle<SiteSettings>(SiteUrl.FormatUrl("StoreManagement_GetSiteSetting", false)) ?? new SiteSettings();
                    KevinCache.Insert(CacheKeys.CacheKeySiteSettings, setting);
                }
                else
                {
                    setting = KevinCache.Get(CacheKeys.CacheKeySiteSettings) as SiteSettings;
                }
                return setting;
            }
        }
        public string WareHouseNumber
        {
            get
            {
                return "000001";
            }
        }

        public string FileServerDomain
        {
            get
            {
                string domain = string.Empty;
                if (!KevinCache.Exists("FileServerDomain"))
                {
                    var obj = RestfulHelper.QueryWithSingle<object>(SiteUrl.FormatUrl("Common_GetFileServerDomain"));
                    if (obj != null)
                    {
                        domain = obj.ToString();
                        KevinCache.Insert("FileServerDomain", domain);
                    }
                }
                else
                {
                    domain = KevinCache.Get("FileServerDomain").ToString();
                }
                return domain;
            }
        }

        public string FileFileServerUpToken
        {
            get
            {
                string upToken = string.Empty;
                var obj = RestfulHelper.QueryWithSingle<object>(SiteUrl.FormatUrl("Common_GetFileServerUpToken"));
                if (obj != null)
                {
                    upToken = obj.ToString();
                }
                return upToken;
            }
        }
    }
}
